<script setup lang="ts">
import type { TocItem } from '@/types/article.ts';
import { ref, onMounted, onUnmounted } from 'vue';
import ArticleTocItem from '@/views/detail/components/ArticleTocItem.vue';
defineProps<{
  tocItems: TocItem[];
}>();
// 追踪当前激活的目录项
const activeId = ref('');
// 监听滚动，高亮当前阅读的段落
const handleScroll = () => {
  const headings = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'));
  for (let i = headings.length - 1; i >= 0; i--) {
    const heading = headings[i];
    const rect = heading.getBoundingClientRect();
    if (rect.top <= 200) {  // 可以调整这个值来改变触发位置
      activeId.value = heading.id;
      break;
    }
  }
};
const handleClick = (id: string) => {
  const element = document.querySelector('#' + id);
  if (element) {
    const elementPosition = element.getBoundingClientRect().top;
    const offsetPosition = elementPosition + window.pageYOffset - 100; // 这里的 100 是顶部偏移量

    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });

    activeId.value = id;
  }
};
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
  handleScroll(); // 初始化
});
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<template>
  <div v-if="tocItems?.length > 0" class="article-detail-contents box-radius">
    <div class="contents-header">
      <span class="icon">📑</span>
      <span class="title">目录</span>
    </div>
    <div class="contents-body">
      <ArticleTocItem
        v-for="item in tocItems"
        :key="item.id"
        :item="item"
        :active-id="activeId"
        :on-item-click="handleClick"
      />
    </div>
  </div>
</template>

<style scoped lang="less">
.article-detail-contents {
  width: 100%;
  background-color: #ffffff;
  padding: 20px;
  max-height: min(600px, calc(100vh - 120px));
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  // 目录头部样式
  .contents-header {
    flex-shrink: 0; // 防止头部被压缩
    display: flex;
    align-items: center;
    gap: 12px;
    padding-bottom: 16px;
    margin-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .icon {
      font-size: 18px;
      color: #60a5fa;
    }

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #1a1a1a;
      font-family: 'Noto Sans SC', sans-serif;
    }
  }

  // 目录内容区域
  .contents-body {
    flex: 1; // 占据剩余空间
    overflow-y: auto;
    padding-right: 8px;
    margin-right: -8px; // 补偿padding-right，使滚动条贴边

    // 滚动条样式
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: #e5e7eb;
      border-radius: 2px;

      &:hover {
        background: #d1d5db;
      }
    }
  }
}
</style>
